﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace PHRClient
{
    public static class XmlExtensions
    {

        /// <summary>
        /// Deserializes the XML data contained by the specified System.String
        /// </summary>
        /// <typeparam name="T">The type of System.Object to be deserialized</typeparam>
        /// <param name="s">The System.String containing XML data</param>
        /// <returns>The System.Object being deserialized.</returns>
        public static T XmlDeserialize<T>(this string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                return default(T);
            }

            var locker = new object();
            var stringReader = new StringReader(s);
            var reader = new XmlTextReader(stringReader);
            try
            {
                var xmlSerializer = new XmlSerializer(typeof(T));
                lock (locker)
                {
                    var item = (T)xmlSerializer.Deserialize(reader);
                    reader.Close();
                    return item;
                }
            }
            catch
            {
                return default(T);
            }
            finally
            {
                reader.Close();
            }
        }

        /// <summary>
        /// Deserializes the XML data contained in the specified file.
        /// </summary>
        /// <typeparam name="T">The type of System.Object to be deserialized.</typeparam>
        /// <param name="fileInfo">This System.IO.FileInfo instance.</param>
        /// <returns>The System.Object being deserialized.</returns>
        public static T XmlDeserialize<T>(this FileInfo fileInfo)
        {
            string xml = string.Empty;
            using (FileStream fs = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    T tt = sr.ReadToEnd().XmlDeserialize<T>();
                    return tt;
                }
            }
        }

        /// <summary>
        /// <para>Serializes the specified System.Object and writes the XML document</para>
        /// <para>to the specified file.</para>
        /// </summary>
        /// <typeparam name="T">This item's type</typeparam>
        /// <param name="item">This item</param>
        /// <param name="fileName">The file to which you want to write.</param>
        /// <returns>true if successful, otherwise false.</returns>
        public static bool XmlSerialize<T>(this T item, string fileName)
        {
            return item.XmlSerialize(fileName, true);
        }

        /// <summary>
        /// <para>Serializes the specified System.Object and writes the XML document</para>
        /// <para>to the specified file.</para>
        /// </summary>
        /// <typeparam name="T">This item's type</typeparam>
        /// <param name="item">This item</param>
        /// <param name="fileName">The file to which you want to write.</param>
        /// <param name="removeNamespaces">
        ///     <para>Specify whether to remove xml namespaces.</para>para>
        ///     <para>If your object has any XmlInclude attributes, then set this to false</para>
        /// </param>
        /// <returns>true if successful, otherwise false.</returns>
        public static bool XmlSerialize<T>(this T item, string fileName, bool removeNamespaces)
        {
            object locker = new object();

            XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
            xmlns.Add(string.Empty, string.Empty);

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.OmitXmlDeclaration = true;

            lock (locker)
            {

                XmlDocument doc = new XmlDocument();
                doc.Load(fileName);

                if (typeof(T).Equals(typeof(PatientDataCollection)))
                {

                    XmlNode xnode = doc.CreateNode(XmlNodeType.Element, "PatientData", null);

                    StringWriter stringwriter = new StringWriter();
                    using (XmlWriter xmlwriter = System.Xml.XmlWriter.Create(stringwriter, settings))
                    {
                        xmlSerializer.Serialize(xmlwriter, item, xmlns);
                    }

                    xnode.InnerXml = stringwriter.ToString();
                    XmlNode bindxnode = xnode.SelectSingleNode("PatientDetails");

                    XmlNodeList xnList = xnode.SelectNodes("/PatientDetails/PatientData");

                    string ID = xnList[0]["UserId"].InnerText;
                    string DT = xnList[0]["RecordDate"].InnerText;
                    string WG = xnList[0]["Weight"].InnerText;
                    string BT = xnList[0]["BodyTemp"].InnerText;
                    string HR = xnList[0]["HeartRate"].InnerText;
                    string CTRI = xnList[0]["CholestrolTri"].InnerText;
                    string CHDL = xnList[0]["CholestrolHdl"].InnerText;
                    string CLDL = xnList[0]["CholestrolLdl"].InnerText;
                    string BPS = xnList[0]["BloodPressureSys"].InnerText;
                    string BPD = xnList[0]["BloodPressureDia"].InnerText;
                    string PR = xnList[0]["PulseRate"].InnerText;
                    string GLU = xnList[0]["Glucose"].InnerText;


                    XmlNode newsd = doc.CreateNode(XmlNodeType.Element, "PatientData", null);

                    XmlElement elem = doc.CreateElement("UserId");
                    elem.InnerText = ID;
                    newsd.AppendChild(elem);

                    XmlElement elem2 = doc.CreateElement("RecordDate");
                    elem2.InnerText = DT;
                    newsd.AppendChild(elem2);

                    XmlElement elem3 = doc.CreateElement("Weight");
                    elem3.InnerText = WG;
                    newsd.AppendChild(elem3);

                    XmlElement elem4 = doc.CreateElement("BodyTemp");
                    elem4.InnerText = BT;
                    newsd.AppendChild(elem4);

                    XmlElement elem5 = doc.CreateElement("HeartRate");
                    elem5.InnerText = HR;
                    newsd.AppendChild(elem5);

                    XmlElement elem6 = doc.CreateElement("CholestrolTri");
                    elem6.InnerText = CTRI;
                    newsd.AppendChild(elem6);

                    XmlElement elem7 = doc.CreateElement("CholestrolHdl");
                    elem7.InnerText = CHDL;
                    newsd.AppendChild(elem7);

                    XmlElement elem8 = doc.CreateElement("CholestrolLdl");
                    elem8.InnerText = CLDL;
                    newsd.AppendChild(elem8);

                    XmlElement elem9 = doc.CreateElement("BloodPressureSys");
                    elem9.InnerText = BPS;
                    newsd.AppendChild(elem9);

                    XmlElement elem10 = doc.CreateElement("BloodPressureDia");
                    elem10.InnerText = BPD;
                    newsd.AppendChild(elem10);

                    XmlElement elem11 = doc.CreateElement("PulseRate");
                    elem11.InnerText = PR;
                    newsd.AppendChild(elem11);

                    XmlElement elem12 = doc.CreateElement("Glucose");
                    elem12.InnerText = GLU;
                    newsd.AppendChild(elem12);

                    doc.DocumentElement.AppendChild(newsd);
                    doc.Save(fileName);


                }
                else if (typeof(T).Equals(typeof(PatientCollection)))
                {
                    XmlNode xnode = doc.CreateNode(XmlNodeType.Element, "Patient", null);

                    StringWriter stringwriter = new StringWriter();
                    using (XmlWriter xmlwriter = System.Xml.XmlWriter.Create(stringwriter, settings))
                    {
                        xmlSerializer.Serialize(xmlwriter, item, xmlns);
                    }

                    xnode.InnerXml = stringwriter.ToString();
                    XmlNode bindxnode = xnode.SelectSingleNode("PatientInfo");

                    XmlNodeList xnList = xnode.SelectNodes("/PatientInfo/Patient");

                    string ID = xnList[0]["PatientId"].InnerText;
                    string DT = xnList[0]["Name"].InnerText;
                    string WG = xnList[0]["Address"].InnerText;
                    string BT = xnList[0]["Tel"].InnerText;
                    string HR = xnList[0]["Gender"].InnerText;
                    string CTRI = xnList[0]["Birthday"].InnerText;
                    string CHDL = xnList[0]["HeightCm"].InnerText;
                    string CLDL = xnList[0]["WeightKg"].InnerText;
                    string UN = xnList[0]["UserName"].InnerText;
                    string PW = xnList[0]["Password"].InnerText;

                    XmlNode newsd = doc.CreateNode(XmlNodeType.Element, "Patient", null);

                    XmlElement elem = doc.CreateElement("PatientId");
                    elem.InnerText = ID;
                    newsd.AppendChild(elem);

                    XmlElement elem0 = doc.CreateElement("UserName");
                    elem0.InnerText = UN;
                    newsd.AppendChild(elem0);

                    XmlElement elem00 = doc.CreateElement("Password");
                    elem00.InnerText = PW;
                    newsd.AppendChild(elem00);

                    XmlElement elem2 = doc.CreateElement("Name");
                    elem2.InnerText = DT;
                    newsd.AppendChild(elem2);

                    XmlElement elem3 = doc.CreateElement("Address");
                    elem3.InnerText = WG;
                    newsd.AppendChild(elem3);

                    XmlElement elem4 = doc.CreateElement("Tel");
                    elem4.InnerText = BT;
                    newsd.AppendChild(elem4);

                    XmlElement elem5 = doc.CreateElement("Gender");
                    elem5.InnerText = HR;
                    newsd.AppendChild(elem5);

                    XmlElement elem6 = doc.CreateElement("Birthday");
                    elem6.InnerText = CTRI;
                    newsd.AppendChild(elem6);

                    XmlElement elem7 = doc.CreateElement("HeightCm");
                    elem7.InnerText = CHDL;
                    newsd.AppendChild(elem7);

                    XmlElement elem8 = doc.CreateElement("WeightKg");
                    elem8.InnerText = CLDL;
                    newsd.AppendChild(elem8);

                    doc.DocumentElement.AppendChild(newsd);
                    doc.Save(fileName);

                }
                else
                {
                }

            }

            return true;
        }
    }
}
